package com.zbf.moredb.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  13:46
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.zbf.moredb.dao2"},sqlSessionFactoryRef="sqlSessionFactory2")
public class DataSource2Config {

    @Bean("dataSource2")
    public DataSource getDataSource1(DataSource2Properties dataSource2Properties){

        DataSource build = DataSourceBuilder.create().url(dataSource2Properties.getUrl())
                .username(dataSource2Properties.getUsername())
                .password(dataSource2Properties.getPassword())
                .driverClassName(dataSource2Properties.getDriverClassName())
                .build();

        return build;
    }


    @Bean("transactionManager2")
    public DataSourceTransactionManager getDataSourceTransactionManager1(@Qualifier("dataSource2") DataSource dataSource){

        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);

        return dataSourceTransactionManager;

    }

    @Bean("sqlSessionFactory2")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/db2/*.xml"));

        return sqlSessionFactoryBean.getObject();

    }

}
